package com.neo.productitsms.pro.third.chart;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.constraint.ConstraintLayout;
import android.view.View;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.neo.productitsms.R;
import com.neo.productitsms.mvp.presenter.impl.MvpBasePresenter;
import com.neo.productitsms.pro.base.view.activity.BaseActivtiy;
import com.neo.productitsms.pro.third.chart.entity.CompositeIndexBean;
import com.neo.productitsms.pro.third.chart.entity.IncomeBean;
import com.neo.productitsms.pro.third.chart.entity.LineChartBean;
import com.neo.productitsms.pro.third.chart.utils.AssertUtils;
import com.neo.productitsms.pro.third.chart.utils.DateUtils;
import com.neo.productitsms.pro.third.chart.view.LineChartMarkView;
import com.neo.productitsms.utils.GsonUtil;
import com.neo.productitsms.utils.LogUtils;

import java.nio.file.NotLinkException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/10/15.
 */

public class DemoLines extends BaseActivtiy {
    @BindView(R.id.lineChart)
    LineChart mLineChart;
    @BindView(R.id.view_mine)
    View viewMine;
    @BindView(R.id.view_shanghai)
    TextView viewShanghai;
    @BindView(R.id.cl_shanghai)
    ConstraintLayout clShanghai;
    @BindView(R.id.view_shenzhen)
    View viewShenzhen;
    @BindView(R.id.cl_shenzhen)
    ConstraintLayout clShenzhen;
    @BindView(R.id.view_gem)
    View viewGem;
    @BindView(R.id.cl_gem)
    ConstraintLayout clGem;
    private XAxis xAxis;
    private YAxis leftYAxis;
    private YAxis rightYaxis;
    private String lineChartDataJson;
    private Legend legend;
    private List<IncomeBean> listLineData;
    private List<CompositeIndexBean> shanghai;
    private List<CompositeIndexBean> shenzhen;

    @Override
    public MvpBasePresenter bindPresenter() {
        return null;
    }

    @Override
    protected int layoutResId() {
        return R.layout.activity_demos_linechart;
    }

    @Override
    protected void initData() {

        lineChartDataJson = AssertUtils.getJson(this, "line_chart.json");

        LogUtils.i("读取到的数据：" + lineChartDataJson);

        LineChartBean lineChartBean = GsonUtil.GsonToBean(lineChartDataJson, LineChartBean.class);

        listLineData = lineChartBean.getGRID0().getResult().getClientAccumulativeRate();

        shanghai = lineChartBean.getGRID0().getResult().getCompositeIndexShanghai();
        shenzhen = lineChartBean.getGRID0().getResult().getCompositeIndexShenzhen();

    }

    @Override
    protected void initView() {


        initChart(mLineChart);


//        showLineChart(listLineData, "我的收益", Color.CYAN);
        showLineChart(listLineData, "我的收益", getResources().getColor(R.color.blue));
        Drawable drawable = getResources().getDrawable(R.drawable.fade_blue);
        setChartFillDrawable(drawable);
        setMarkView();

        addLine(shanghai, "上证指数", getResources().getColor(R.color.orange));
//        addLine(shenzhen, "深证指数", getResources().getColor(R.color.green));

    }


    /**
     * 初始化图表
     */
    private void initChart(LineChart lineChart) {
        /***图表设置***/

//        //是否显示边界
//        lineChart.setDrawBorders(true);

//        设置 背景 去掉 边界
        lineChart.setBackgroundColor(Color.WHITE);
        lineChart.setDrawBorders(false);

        //是否展示网格线
        lineChart.setDrawGridBackground(false);


        //是否可以拖动
        lineChart.setDragEnabled(false);
        //是否有触摸事件
        lineChart.setTouchEnabled(true);
        //设置XY轴动画效果
        lineChart.animateY(2500);
        lineChart.animateX(1500);


        /***XY轴的设置***/
        xAxis = lineChart.getXAxis();
        leftYAxis = lineChart.getAxisLeft();
        rightYaxis = lineChart.getAxisRight();
        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        //保证Y轴从0开始，不然会上移一点
        leftYAxis.setAxisMinimum(0f);
        rightYaxis.setAxisMinimum(0f);
//但还是显示了网格线，而且不是我们想要的 虚线 。其实那是 X Y轴自己的网格线，禁掉即可 106
//        lineChart.setDrawGridBackground(false);

        xAxis.setDrawGridLines(false);
        leftYAxis.setDrawGridLines(false);
        rightYaxis.setDrawGridLines(false);

        rightYaxis.setEnabled(false);

//        设置X Y轴网格线为虚线（实体线长度、间隔距离、偏移量：通常使用 0）
        leftYAxis.enableAxisLineDashedLine(10f, 10f, 0f);


        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                String tradeDate = listLineData.get((int) value % listLineData.size()).getTradeDate();
//                LogUtils.e("获取的时间："+tradeDate+";;"+listLineData.get((int) value).getTradeDate());

                return DateUtils.formatDate(tradeDate);

            }
        });

//        设置X轴 分割数量 true 代表 强制均分
        xAxis.setLabelCount(6, false);


        leftYAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return ((int) (value * 100)) + "%";
            }
        });


        leftYAxis.setLabelCount(8);
        /***折线图例 标签 设置***/
        legend = lineChart.getLegend();
        //设置显示类型，LINE CIRCLE SQUARE EMPTY 等等 多种方式，查看LegendForm 即可
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(12f);
        //显示位置 左下方
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);
    }

    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     *
     * @param lineDataSet 线条
     * @param color       线条颜色
     * @param mode
     */
    private void initLineDataSet(final LineDataSet lineDataSet, int color, LineDataSet.Mode mode) {

        lineDataSet.setColor(color);
        lineDataSet.setCircleColor(color);
        lineDataSet.setLineWidth(1f);
        lineDataSet.setCircleRadius(3f);
//        设置曲线值 原点是 实心还是 空心
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setValueTextSize(10f);
//        设置 折线图 填充
        lineDataSet.setDrawFilled(true);
        lineDataSet.setFormLineWidth(1f);
        lineDataSet.setFormSize(15f);
//不显示 点
//        lineDataSet.setDrawCircles(false);


        if (mode == null) {
            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        } else {
            lineDataSet.setMode(mode);
        }


        lineDataSet.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                DecimalFormat df = new DecimalFormat(".00");

                return df.format(value * 100) + "%";
            }
        });

        lineDataSet.setDrawValues(false);

    }

    public void showLineChart(List<IncomeBean> dataList, String name, int color) {

        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {

            IncomeBean data = dataList.get(i);

            /**
             * 在此可查看 Entry构造方法，可发现 可传入数值 Entry(float x, float y)
             * 也可传入Drawable， Entry(float x, float y, Drawable icon) 可在XY轴交点 设置Drawable图像展示
             */

            Entry entry = new Entry(i, (float) data.getValue());

            entries.add(entry);

        }

//        每一个 lineDataSet  代表 一条线
        LineDataSet lineDataSet = new LineDataSet(entries, name);
        initLineDataSet(lineDataSet, color, LineDataSet.Mode.LINEAR);
        LineData lineData = new LineData(lineDataSet);
        mLineChart.setData(lineData);

    }


    public void setChartFillDrawable(Drawable drawable) {

        if (mLineChart.getData() != null && mLineChart.getData().getDataSetCount() > 0) {

            LineDataSet lineDataSet = (LineDataSet) mLineChart.getData().getDataSetByIndex(0);
//避免在 initLineDataSet 方法中 设置了 lineDataSet。setDrawble(false);而 无法实现 效果
            lineDataSet.setDrawFilled(true);
            lineDataSet.setFillDrawable(drawable);
            mLineChart.invalidate();

        }


    }

    public void setMarkView() {

        LineChartMarkView mv = new LineChartMarkView(this, xAxis.getValueFormatter());
        mv.setChartView(mLineChart);
        mLineChart.setMarker(mv);
        mLineChart.invalidate();

    }


    /**
     * 添加 曲线
     */
    private void addLine(List<CompositeIndexBean> dataList, String name, int color) {

        List<Entry> entries = new ArrayList<>();

        for (int i = 0; i < dataList.size(); i++) {

            CompositeIndexBean data = dataList.get(i);

            Entry entry = new Entry(i, ((float) data.getRate()));

            entries.add(entry);

        }

        LineDataSet lineDataSet = new LineDataSet(entries, name);
        initLineDataSet(lineDataSet, color, LineDataSet.Mode.LINEAR);
        mLineChart.getLineData().addDataSet(lineDataSet);

        mLineChart.invalidate();
    }


}
